package org.simple.wechat.demo.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.simple.wechat.demo.ienum.IEnum;
import org.simple.wechat.demo.utils.IEnumUtils;

import java.io.IOException;
import java.lang.reflect.Field;

/***
 * @author gaoqijin
 * @date 2020-9-10
 * @Description
 */
public class IEnumDeserializer extends JsonDeserializer<IEnum> {
  @Override
  public IEnum deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
      throws IOException, JsonProcessingException {
    String valueAsString = jsonParser.getValueAsString();
    IEnum enumByCode = null;
    try {
      Class<?> aClass = jsonParser.getParsingContext().getCurrentValue().getClass();
      String enumProperty = jsonParser.getParsingContext().getCurrentName();
      Field enumField = aClass.getDeclaredField(enumProperty);
      if (enumField.getType().isEnum()) {
        Class enumClass = enumField.getType();
        enumByCode = IEnumUtils.getEnumByCode(valueAsString, enumClass);
      }
    } catch (NoSuchFieldException e) {
      e.printStackTrace();
      //todo
    }
    return enumByCode;
  }
}
